import React, { Component } from 'react';
import { withRouter } from 'react-router-dom';
import { Form, Input, Button, message } from 'antd';
import axios from './../../axios/index';
import './index.less';

class ChangePwd extends Component {
	
	formRef = React.createRef();
	
	//保存修改
	onFinish = values => {
		if(values.new_pwd !== values.new_pwd_confirm){
			message.error("新密码与确认密码不一致");
		}else{
			axios.ajax({
				url: "/User/Operate/changePwd",
				method: "post",
				data: values
			}).then(res=>{
				if(res.code === 0){
					message.success(res.msg+"，请重新登陆");
					this.props.history.push("/login");
				}else{
					message.error("修改失败");
					this.onReset();
				}
			}).catch(err=>{
				this.onReset();
			})
		}
	};
	
	//重置
	onReset = () => {
		this.formRef.current.resetFields();
	};
	
	render(){
		const layout = {
		    labelCol: { span: 4 },
		    wrapperCol: { span: 20 },
		};
		const tailLayout = {
		    wrapperCol: { offset: 4, span: 20 },
		};
		return (
			<div className="pwd-wrap">
				<div className="pwd-content">
					<div className="title">修改密码</div>
					<Form {...layout} ref={this.formRef} name="control-hooks" onFinish={this.onFinish}>
						<Form.Item
							name="old_pwd"
							label="当前密码"
							hasFeedback
							rules={[
							    {required: true, message: "请输入当前密码"},
							    {min:6,max:18,message:"请输入6-18个字符"},
							    {pattern: /^[a-z0-9_]{3,16}$/, message: "不符合格式"}
							]}
						>
							<Input.Password autoComplete="off" />
						</Form.Item>
						<Form.Item
							name="new_pwd"
							label="新密码"
							hasFeedback
							rules={[
							    {required: true, message: "请输入密码"},
							    {min:6,max:18,message:"请输入6-18个字符"},
							    {pattern: /^[a-z0-9_]{3,16}$/, message: "不符合格式"}
							]}
						>
							<Input.Password autoComplete="off" />
						</Form.Item>
						<Form.Item
							name="new_pwd_confirm"
							label="再次确认"
							hasFeedback
							rules={[
							    {required: true, message: "请输入密码"},
							    {min:6,max:18,message:"请输入6-18个字符"},
							    {pattern: /^[a-z0-9_]{3,16}$/, message: "不符合格式"}
							]}
						>
							<Input.Password autoComplete="off" />
						</Form.Item>
						<Form.Item  {...tailLayout} style={{textAlign: "center"}}>
							<Button type="primary" htmlType="submit">
							    保存
							</Button>
							<Button htmlType="button" onClick={this.onReset}>
								重置
							</Button>
						</Form.Item>
					</Form>
				</div>
			</div>
		)
	}
}

export default withRouter(ChangePwd);